
package com.by.toolkit.utils;

import java.util.function.Supplier;

/**
 * 描述：条件判断，减少if else
 *
 * @author liujun
 * @date 2023年06月13 8:57 PM
 */
public class ByIfTrueUtil {

    private ByIfTrueUtil() {

    }

    /**
     * @param condition    条件
     * @param trueSupplier true时执行
     * @param defaultVal   false时返回
     * @return 返回
     */
    public static <T> T getIfTrue(boolean condition, Supplier<T> trueSupplier, T defaultVal) {
        if (condition) {
            return trueSupplier.get();
        } else {
            return defaultVal;
        }
    }


    /**
     * @param condition     条件
     * @param trueSupplier  true时执行
     * @param falseSupplier false时执行
     * @return 返回
     */
    public static <T> T getIfTrueOrElse(boolean condition, Supplier<T> trueSupplier, Supplier<T> falseSupplier) {
        if (condition) {

            return trueSupplier.get();
        } else {
            return falseSupplier.get();
        }
    }


    /**
     * @param condition    条件
     * @param trueRunnable true时执行
     */
    public static void doIfTrue(boolean condition, ByRunnable trueRunnable) {
        if (condition) {
            trueRunnable.run();
        }
    }

    /**
     * @param condition     条件
     * @param trueRunnable  true执行
     * @param falseRunnable false执行
     */
    public static void doIfTrueOrElse(boolean condition, ByRunnable trueRunnable, ByRunnable falseRunnable) {
        if (condition) {
            trueRunnable.run();
        } else {
            falseRunnable.run();
        }
    }

    /**
     * @param condition     条件
     * @param trueSupplier  true执行
     * @param falseSupplier false执行
     * @param <T>           泛型
     * @return supplier.get
     */
    public static <T> T getIfTrueOrElseThrow(boolean condition, Supplier<T> trueSupplier,
                                             Supplier<? extends RuntimeException> falseSupplier) {
        if (condition) {
            return trueSupplier.get();
        } else {
            throw falseSupplier.get();
        }
    }

    /**
     * @param condition         判断
     * @param exceptionSupplier 异常supplier
     */
    public static void throwIfTrue(boolean condition, Supplier<? extends RuntimeException> exceptionSupplier) {
        if (condition) {
            throw exceptionSupplier.get();
        }
    }

    /**
     * @param condition         判断
     * @param exceptionSupplier 异常supplier
     */
    public static void throwIfFalse(boolean condition, Supplier<? extends RuntimeException> exceptionSupplier) {
        if (!condition) {
            throw exceptionSupplier.get();
        }
    }
}

